package kr.hkit.powerjava.chapter24.work3;

import java.util.Comparator;
import java.util.Scanner;
import kr.hkit.powerjava.chapter24.work2.dao.StudentDao;
import kr.hkit.powerjava.chapter24.work2.vo.Student;

public class ServiceStudent_work2에서버림받음 {

	/*
	 * 1. 시작 (Student Dao 객체 생성 후 loadFile()까지) 2. 메뉴보이기 (prnMenu) 3. 종료
	 * (StudentDao.saveFile())
	 */

	protected StudentDao dao;
	private Scanner sc;

	
	
	public ServiceStudent_work2에서버림받음() {
		dao = new StudentDao();
		sc = new Scanner(System.in);
		init();
	}

	public ServiceStudent_work2에서버림받음(StudentDao dao) {
		this.dao = dao;
		sc = new Scanner(System.in);
		init();
	}

	private void init() {
		dao.loadFile();
		prnMenu();
	}

	private void prnMenu() {
		int res = 0;
		Student std = null;
		do {
			System.out.print("1. 입력\n2. 삭제\n3. 수정\n4. 검색\n5. 리스트보기\n6. 종료\n");
			res = sc.nextInt();
			switch (res) {
			
			case 1:// 학생정보입력
				std = inputStdInfo(true);
				dao.insertItem(std);
				break;
				
			case 2:
				//리스트를 보여주고 삭제할 번호를 입력받음
				dao.prnItemList(null);
				System.out.print("삭제할 학생 정보를 입력하세요: ");
				std = inputStdInfo(false);
				dao.deleteItem(std);
				break;
				
			case 3:
				//리스트를 보여주고 수정할 학생정보를 입력받아
				dao.prnItemList(null);
				std = inputStdInfo(true);
				dao.updateItem(std);
				break;
				
			case 4:
				std = inputStdInfo(false);
				try{
					std = dao.searchItem(std);
					System.out.println(std);
				} catch(ArrayIndexOutOfBoundsException e){
					System.out.println("해당 학생 정보 없음");
				}
				break;
				
			case 5:
				prnSubMenu();
				break;
				
			case 6:
				dao.saveFile();
				sc.close();
				System.exit(0);
				break;
			default:
				res = 5;
			}
		} while (res <= 6);
	}

	private Student inputStdInfo(boolean gubun) {
		System.out.print("학번 성명");
		int num = sc.nextInt();
		String name = sc.next();

		if (gubun) {
			System.out.print("국어 영어 수학");
			int kor = sc.nextInt();
			int eng = sc.nextInt();
			int math = sc.nextInt();

			return new Student(num, name, kor, eng, math);
		} else {
			return new Student(num, name);
		}
	}

	private void prnSubMenu() {
		System.out.print("1. 이름순 정렬\n2. 성적순 정렬\n3. 번호순 정렬");
		int res = sc.nextInt();

		switch (res) {
		case 1:
			dao.prnItemList(new Comparator<Student>() {

				@Override
				public int compare(Student o1, Student o2) {
					return o1.getStdName().hashCode()
							- o2.getStdName().hashCode();
				}
			});
			break;
		case 2:
			dao.prnItemList(new Comparator<Student>() {

				@Override
				public int compare(Student o1, Student o2) {
					return o1.totalScore() - o2.totalScore();
				}
			});
			break;
		case 3:
			dao.prnItemList(null);
			break;
		default:
			dao.prnItemList(null);
		}
	}
}
